package com.it2297.component;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

public class ImageChooser
{
	private final JFileChooser fc;
	private final FileFilter imageFilter = new FileNameExtensionFilter("Images", ImageIO.getReaderFileSuffixes());
	private File file;
	private File[] files;
	private BufferedImage bimg;
	private BufferedImage[] bimgs;

	public ImageChooser()
	{
		// WebLookAndFeel has not yet implement the theme on JFileChooser.
		// Switch back to use system default theme temporarily.
		try
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}

		// initiate file chooser dialog
		// setup file filter to accept only images
		fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fc.setFileFilter(imageFilter);
		fc.setAcceptAllFileFilterUsed(false);
		fc.addChoosableFileFilter(imageFilter);
	}

	public void showDialog()
	{
		int state = fc.showOpenDialog(null);
		if (state == JFileChooser.APPROVE_OPTION)
		{
			if (fc.isMultiSelectionEnabled())
			{
				files = fc.getSelectedFiles();
				
				bimgs = createBufferedImages(files);
			}
			else
			{
				// receive raw file
				file = fc.getSelectedFile();

				// convert file to buffered image
				bimg = createBufferedImage(file);
			}
		}

		// Switch back on WebLookAndFeel after the file chooser has been
		// instantiated
		try
		{
			UIManager.setLookAndFeel("com.alee.laf.WebLookAndFeel");
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}

	public void setMultiSelectionEnabled(boolean b)
	{
		fc.setMultiSelectionEnabled(b);
	}
	
	public boolean isMultiSelectionEnabled(){
		return fc.isMultiSelectionEnabled();
	}

	public BufferedImage getSelectedImage()
	{
		return bimg;
	}
	
	public BufferedImage[] getSelectedImages(){
		return bimgs;
	}

	private BufferedImage createBufferedImage(File file)
	{
		BufferedImage _bimg = null;

		try
		{
			_bimg = ImageIO.read(file);
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}

		return _bimg;
	}
	
	private BufferedImage[] createBufferedImages(File[] files){
		BufferedImage[] _bimgs = new BufferedImage[files.length];
		
		for(int i=0; i<files.length;i++){
			_bimgs[i] = createBufferedImage(files[i]);
		}
		
		return _bimgs;
	}
}
